<?php

namespace app\home\home;
use app\admin\controller\Admin;
use app\home\model\User;
use GatewayClient\Gateway;
use think\Db;
use think\Request;
require_once EXTEND_PATH."wokerclient/Gateway.php";

class Chats extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function __construct()
    {
        Gateway::$registerAddress = '127.0.0.1:1236';
    }
    //绑定用户
    public function init(Request $request)
    {

        //绑定用户
        $this->bind($request);
    }

    private function bind($request)
    {
        $data = $request->param();
        $id = $data['id'];
        $client_id = $data['client_id'];
        Gateway::bindUid($client_id, $id);
        if (Gateway::isUidOnline($id)){
            return apistatus(1,'绑定成功');
        }else{
            return apistatus(0,'绑定失败');
        }


    }
    public function save(Request $request){
        $this->saveMessage($request);
    }

    /**
     * 检查免费次数或者红豆币金额是否足够.
     *
     * @return \think\Response
     */
    public function checkTimes(Request $request)
    {
       $data = $request->param();
       $id = $data['id'];
       if (empty($id)){
           return apistatus(0,'用户id不能为空');
       }
       self::checktoken($id);
//       $info = \db('home_users')->where('id',$id)->field('chattimes,rd_coin')->find();
//       if ($info['chattimes'] < 1 && $info['rd_coin']){
//           return apistatus(0,'您的免费打招呼次数已用完,请使用红豆币解锁');
//       }elseif ($info['chattimes'] < 1 && $info['rd_coin'] < 6){
//           return apistatus(2,'您的红豆币余额不足无法解锁打招呼,请充值');
//       }

    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function saveMessage($request)
    {
        //
        $data= $request->param();
        $info1 = db('home_users')
            ->where('id',$data['id'])
            ->field('nickname,headicon,operation_time,role')
            ->find();
        $info2 = db('home_users')
            ->where('id',$data['toid'])
            ->field('nickname,headicon,operation_time,role')
            ->find();
        if ($info2['role'] == 2 || $info2['role'] == 3){
            $data['chat_type'] = 3;
        }
        $infos = [
            'id' => $data['id'],
            'idname' => $info1['nickname'],
            'idheadicon' => $info1['headicon'],
            'toid' => $data['toid'],
            'toidname' => $info2['nickname'],
            'toidheadicon' => $info2['headicon'],
            'message' => $data['message'],
            'message_type' => $data['message_type'],
            'chat_type' => $data['chat_type'],
            'status' => $data['status'],
            'height' => isset($data['height']) ? $data['height'] : 0,
            'width' => isset($data['width']) ? $data['width'] : 0,

        ];
            $message_id = savechatgetid($infos);
            if ($message_id){
                return apistatus(1,'发送成功',$infos);
            }else{
                return apistatus(0,'发送失败');
            }



    }
    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function getChatlist(Request $request)
    {
        //
        $data = $request->param();
        self::checktoken($data['id']);
        $list = Db::query("SELECT T1.id, T1.`fromid`, T1.`toid`, T1.content, T1.create_time,U.nickname,U.headicon,T1.status,T1.message_type from
                (
                SELECT id, `fromid`, `toid`, create_time, content, status,message_type,
                CASE 
                WHEN (`fromid` <= `toid`)
                THEN CONCAT(`fromid`, '-', `toid`) 
                ELSE CONCAT(`toid`, '-', `fromid`) 
                END AS ft from rd_home_chats) AS T1
                INNER JOIN
                (
                SELECT MAX(create_time) AS create_time,
                CASE 
                WHEN (`fromid` <= `toid`)
                THEN CONCAT(`fromid`, '-', `toid`) 
                ELSE CONCAT(`toid`, '-', `fromid`) 
                END AS ft
                from rd_home_chats
                GROUP BY ft  
                ) AS T2
                ON T1.create_time = T2.create_time AND T1.ft = T2.ft
                left join rd_home_users as U on 
                case  WHEN T1.fromid={$data['id']} THEN  T1.toid = U.id
                ELSE  T1.fromid  = U.id  END
                where   T1.`fromid`= {$data['id']}  or  T1.`toid`={$data['id']}");
        if (!empty($list)){
            return apistatus(1,'列表获取成功',$list);
        }else{
            return apistatus(1,'无聊天记录',$list);
        }

    }

    public function consult(Request $request)
    {
        $data = $request->param();
//        self::checktoken($data['id']);
        $isconsult = \db('home_coinrecord')->where(['uid'=>$data['id'],'toid'=>$data['toid'],'status'=>2,'tapid'=>$data['tapid'],'cost_type'=>4])->count();
        $cost = \db('home_tapcost')->where(['uid'=>$data['toid'],'tapid'=>$data['tapid']])->field('cost')->find();
        if ($isconsult){
           return apistatus(1,'该标签您已经咨询过,请开始咨询吧');
        }
        $info = \db('home_users')->where('id',$data['id'])->field('rd_coin,chattimes,role')->find();
        if ($info['role'] !=1 ){
            return apistatus(0,'您没有咨询权限');
        }
        if (empty($info['rd_coin']) || bccomp($info['rd_coin'],$cost['cost'],2) < 0){
            return apistatus(0,'红豆币余额不足',['has_coin'=>0]);
        }

        $rate = config('base.web_rewardrate');
        $costinsert = [
            'uid'=>$data['id'],
            'toid'=>$data['toid'],
            'num'=>$cost['cost'],
            'tapid'=>$data['tapid'],
            'create_time'=>time(),
            'platformdivision'=>$rate,
            'cost_type'=>4,

        ];
        $userupdate = [
            'id'=>$data['id'],
            'rd_coin'=>bcsub($info['rd_coin'],$cost['cost'],2),
        ];
        $t = \db('home_coinrecord')->insertGetId($costinsert);

        if ($t){
            Db::startTrans();
            try{
                \db('home_users')->update($userupdate);
                \db('home_users')->where('id',$data['toid'])->setInc('rd_coin',bcmul($cost['cost'],$rate,2));
                \db('home_coinrecord')->update(['id'=>$t,'status'=>2,'rewardnum'=>bcmul($cost['cost'],$rate,2)]);
                $left = \db('home_users')->where('id',$userupdate['id'])->field('rd_coin')->find();
                // 提交事务
                Db::commit();

                return apistatus(1,'操作成功',['is_consult'=>1,'rd_coin'=>$left['rd_coin']]);
            } catch (\Exception $e) {
                // 回滚事务
                return apistatus(0,'操作失败');
                Db::rollback();
            }
        }else{
            return apistatus(0,'操作失败');
        }

    }


    /**
     * 创建打招呼
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function createChat(Request $request)
    {
        //
        $data = $request->param();
//        self::checktoken($data['id']);
        $cost = config('base.web_chatcoin');
        $ischat = \db('home_coinrecord')->where(['uid'=>$data['id'],'toid'=>$data['toid'],'status'=>2])->count();
        if ($ischat){
            return apistatus(1,'你们已经打过招呼,请直接聊天吧');
        }
        $info = \db('home_users')->where('id',$data['id'])->field('rd_coin,chattimes,role')->find();
        $infoto = \db('home_users')->where('id',$data['toid'])->field('role')->find();

        if ($info['role'] != 1){
            return apistatus(0, '您没有打招呼权限');
        }elseif($info['chattimes'] > 0 && $infoto['role'] == 1){
            $costinsert = [
                'uid'=>$data['id'],
                'toid'=>$data['toid'],
                'num'=>0,
                'create_time'=>time(),
                'cost_type'=>2,

            ];
            $userupdate = [
                'id'=>$data['id'],
                'chattimes'=>$info['chattimes']-1,
            ];
        }elseif($info['chattimes'] < 0 && $infoto['role'] == 1){
            if (empty($info['rd_coin']) || bccomp($info['rd_coin'],$cost,2) < 0){
                return apistatus(0,'红豆币余额不足',['has_coin'=>0]);
            }
            $costinsert = [
                'uid'=>$data['id'],
                'toid'=>$data['toid'],
                'num'=>$cost,
                'create_time'=>time(),
                'cost_type'=>2,

            ];
            $userupdate = [
                'id'=>$data['id'],
                'rd_coin'=>bcsub($info['rd_coin'],$cost,2),
            ];
        }else{
            return apistatus(0,'对方身份不支持打招呼操作');
        }
        $t = Db::table('rd_home_coinrecord')->insertGetId($costinsert);
        if ($t){
            Db::startTrans();
            try{
                Db::table('rd_home_users')->update($userupdate);
                Db::table('rd_home_coinrecord')->update(['id'=>$t,'status'=>2]);
                $left = \db('home_users')->where('id',$data['id'])->value('rd_coin');
                // 提交事务
                Db::commit();
                return apistatus(1,'操作成功',['is_chat'=>1,'rd_coin'=>$left]);
            } catch (\Exception $e) {
                // 回滚事务
                return apistatus(0,'操作失败');
                Db::rollback();
            }
        }else{
            return apistatus(0,'操作失败');
        }
    }
    /**
     * 检查用户是否在聊天界面
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function checkChatPagetype(Request $request)
    {
        $data = $request->param();
        $res = isonchatpage($data['id'],$data['toid']);
        if (!empty($res)){
            return apistatus(1,'在',$res);
        }else{
            return apistatus(0,'不在');
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function changeChatPagetype(Request $request)
    {
        //
        $data = $request->param();
        self::checktoken($data['id']);
        $ison = db('home_chatstatus')->where('fromid',$data['id'])->find();
        if (!$ison){
            db('home_chatstatus')->insert(['fromid'=>$data['id'],'toid'=>$data['toid'],'status'=>2]);
        }else{
            $where['fromid'] = $data['id'];
            $where['toid'] = $data['toid'];
            if ($ison['status'] == 2){
                db('home_chatstatus')->where($where)->update(['status'=>1]);
                return apistatus(1,'更新成功');
            }else{
                db('home_chatstatus')->where($where)->update(['status'=>2]);
                return apistatus(1,'更新成功');

            }
        }

    }

    /**
     * 查看与某个用户的聊天记录
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function seeChatrecord(Request $request)
    {
        $data = $request->param();
        self::checktoken($data['id']);
        isset($data['page']) ? $page = $data['page'] : $page = 1;
        isset($data['listrow']) ? $listrow = $data['listrow'] : $listrow = 10;
        $where['toid'] = ['in',[$data['id'],$data['toid']]];
        $where['fromid'] = ['in',[$data['id'],$data['toid']]];
        $list = \db('home_chats')->where($where)
            ->distinct('fromid,toid')
            ->order('create_time desc')
            ->field('id,content,toid,fromid,create_time,status,message_type,width,height')
            ->paginate($listrow,true,['page'=>$page]);
        if ($list){
            \db('home_chats')->where(['fromid'=>$data['toid'],'toid'=>$data['id']])->update(['status'=>2]);
            return apistatus(1,'加载成功',$list);
        }else{
            return apistatus(1,'无记录',$list);

        }
    }

    /**
     * 查看与某个用户的聊天记录
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function myChatUsers(Request $request)
    {
        $data = $request->param();
//        self::checktoken($data['id']);
        isset($data['page']) ? $page = $data['page'] : $page = 1;
        isset($data['listrow']) ? $listrow = $data['listrow'] : $listrow = 10;
        $where['C.fromid'] = $data['id'];
        $where['U.role'] = $data['role'];
        $list = \db('home_chats')
            ->alias('C')
            ->join('home_users U','C.toid=U.id')
            ->where($where)
            ->distinct('C.toid')
            ->order('C.create_time desc')
            ->field("U.headicon,U.nickname followdname,U.id followdid,U.operation_time,U.gender,U.age,U.introduction,U.address,U.skills,U.role,
               (select count(*) from rd_home_chats C where C.toid=U.id) as chatcount,
               (select count(*) from rd_home_follow F where F.followdid=U.id) as followcount")
            ->paginate($listrow,true,['page'=>$page])->each(function ($item){
                if ($item['operation_time'] > (time()-300)){
                    $item['online'] = '在线';
                }else{
                    $item['online'] = '离线';
                }
                $array = explode(',',$item['skills']);
                $skill['id'] = ['in',$array];
                $skill['type'] = $item['role'];
                $skill['status'] = 1;
                $skills = \db('home_taps')->where($skill)->field('id skillid,name skillname')->limit(3)->select();
                $cost['C.tapid'] = $skills[0]['skillid'];
                $cost['C.uid'] = $item['followdid'];
                $cost['C.status'] = 1;
                $tapcost = \db('home_tapcost')->alias('C')->join('home_taps T','C.tapid=T.id')->where($cost)->field('C.id costid,C.cost,T.name tapname')->limit(1)->find();
                $item['tapcost'] = $tapcost;
                $item['skills'] = $skills;
                return $item;
            });

        if ($list){
            return apistatus(1,'加载成功',$list);
        }else{
            return apistatus(1,'无记录',$list);

        }
    }



}
